//
//  DBEngine.m
//  TravelGuideMdd
//
//  Created by Song Xiaofeng on 13-9-5.
//  Copyright (c) 2013年 mafengwo.com. All rights reserved.
//

#import "DBEngine.h"
//#import "ConstPath.h"
#import "DBHelper.h"
#import "FMDatabaseQueue.h"

#define kFile_database                  [NSString stringWithFormat:@"%@/maindb.sqlite",kPATH_Workshop]

@interface DBEngine ()

@end

@implementation DBEngine
static DBEngine *_sharedInstance = nil;

+ (DBEngine*)sharedInstance;
{
   
	if (_sharedInstance == nil)
	{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _sharedInstance = [[DBEngine alloc] init];
        });
	}
	
	return _sharedInstance;
}

- (void)dealloc
{
    [self.databaseQueue close];
    _databaseQueue = nil;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        [self initialize];
    }
    return self;
}

- (void)initialize
{
    _mainDBPath = kFile_database;
    _databaseQueue = [FMDatabaseQueue databaseQueueWithPath:_mainDBPath];
}


- (NSString*)mainDBPath;
{
    return _mainDBPath;
}

-(void)dbInsertOrUpdateTable:(NSString*)tableName
                   arrayDict:(NSArray*)arrayDict
                       idKey:(NSString*)idKey
                   keyOthers:(NSArray*)otherKeys
{
    [self.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        @try {
            [arrayDict enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                NSDictionary* dict = obj;
                MFWJson* json = [MFWJson jsonWithObject:dict];
                NSString* c_json = [json stringJson];
                NSString* c_id = [json stringValueForKey:idKey];
                
                NSMutableDictionary* columnKeyValueDict = [NSMutableDictionary dictionaryWithCapacity:0];
                [otherKeys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    NSString* columnName = obj;
                    NSString* columnValue = [json stringValueForKey:columnName];
                    
                    if (columnName && columnValue) {
                        [columnKeyValueDict setObject:columnValue forKey:columnName];
                    }
                }];
                
                [DBHelper executeInsertOrUpdateTable:tableName
                                                c_id:c_id
                                              c_json:c_json
                              withColumnKeyValueDict:columnKeyValueDict
                                            database:db];
            }];
        }
        @catch (NSException *exception) {
            // todo 异常处理
            *rollback = YES;
        }
        @finally {
            
        }
    }];
}


/* modify by liuche at 2014-06-30
-(void)dbInsertOrUpdateTable:(NSString*)tableName
                   jsonArray:(MFWJson*)jsonArray
                       idKey:(NSString*)idKey
                   keyOthers:(NSArray*)otherKeys
{
    @synchronized(self.class)
    {
        FMDatabase* db = [FMDatabase databaseWithPath:self.mainDBPath];
        [db open];
        @try {
            NSUInteger count = [jsonArray count];

            for (int i = 0; i < count; i++) {
                MFWJson* json = [jsonArray jsonAtIndex:i];
                NSString* c_json = [json stringJson];
                NSString* c_id = [json stringValueForKey:idKey];
                
                if (!c_id) {
                    NSLog(@"c_id is null!");
                }
                
                NSMutableDictionary* columnKeyValueDict = [NSMutableDictionary dictionaryWithCapacity:0];
                [otherKeys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    NSString* columnName = obj;
                    NSString* columnValue = [json stringValueForKey:columnName];
                    
                    if (columnName && columnValue) {
                        [columnKeyValueDict setObject:columnValue forKey:columnName];
                    }
                }];
                
                [DBHelper executeInsertOrUpdateTable:tableName
                                                c_id:c_id
                                              c_json:c_json
                              withColumnKeyValueDict:columnKeyValueDict
                                            database:db];
            }
        }
        @catch (NSException *exception) {
            // todo 异常处理
        }
        @finally {
            [db close];
        }
    }
}
*/

/*
//刘澈在2014-6-30 重写上面的函数，因为在城市选择页面的时候插入的数据量大没有用事务的话会产生瓶颈
-(void)dbInsertOrUpdateTable:(NSString*)tableName
                   jsonArray:(MFWJson*)jsonArray
                       idKey:(NSString*)idKey
                   keyOthers:(NSArray*)otherKeys
{
  FMDatabaseQueue *dataBaseQueue = [FMDatabaseQueue databaseQueueWithPath:self.mainDBPath];
    [dataBaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback){
        [db open];
        @try {
            NSUInteger count = [jsonArray count];
            for (int i = 0; i < count; i++) {
                MFWJson* json = [jsonArray jsonAtIndex:i];
                NSString* c_json = [json stringJson];
                NSString* c_id = [json stringValueForKey:idKey];
                
                if (!c_id) {
                    NSLog(@"c_id is null!");
                }
                
                NSMutableDictionary* columnKeyValueDict = [NSMutableDictionary dictionaryWithCapacity:0];
                [otherKeys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    NSString* columnName = obj;
                    NSString* columnValue = [json stringValueForKey:columnName];
                    
                    if (columnName && columnValue) {
                        [columnKeyValueDict setObject:columnValue forKey:columnName];
                    }
                }];
                
                [DBHelper executeInsertOrUpdateTable:tableName
                                                c_id:c_id
                                              c_json:c_json
                              withColumnKeyValueDict:columnKeyValueDict
                                            database:db];
            }
            BOOL success = [db commit];
            if(!success){
                [db rollback];
            }
        }
        @catch (NSException *exception) {
            // todo 异常处理
            [db rollback];
        }
        @finally {
            [db close];
        }
    }];
}
*/

-(void)dbInsertOrUpdateTable:(NSString*)tableName
                   jsonArray:(MFWJson*)jsonArray
                       idKey:(NSString*)idKey
                   keyOthers:(NSArray*)otherKeys
{
    [self.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback){
        @try {
            NSUInteger count = [jsonArray count];
            for (int i = 0; i < count; i++) {
                MFWJson* json = [jsonArray jsonAtIndex:i];
                NSString* c_json = [json stringJson];
                NSString* c_id = [json stringValueForKey:idKey];
                
                if (!c_id) {
                    NSLog(@"c_id is null!");
                }
                
                NSMutableDictionary* columnKeyValueDict = [NSMutableDictionary dictionaryWithCapacity:0];
                [otherKeys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    NSString* columnName = obj;
                    NSString* columnValue = [json stringValueForKey:columnName];
                    
                    if (columnName && columnValue) {
                        [columnKeyValueDict setObject:columnValue forKey:columnName];
                    }
                }];
                
                [DBHelper executeInsertOrUpdateTable:tableName
                                                c_id:c_id
                                              c_json:c_json
                              withColumnKeyValueDict:columnKeyValueDict
                                            database:db];
            }
        }
        @catch (NSException *exception) {
            *rollback = YES;
        }
    }];
}


-(void)dbDeleteTable:(NSString*)tableName
            arrayIds:(NSArray*)arrayIds
{
    [self.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        @try {
            [DBHelper executeDeleteTable:tableName c_ids:arrayIds database:db];
        }
        @catch (NSException *exception) {
            // todo 异常处理
            *rollback = YES;
        }
        @finally {
            /* 在databasequeue 里的block不能close db，否则，该db就被close了 */
//            [db close];
        }
    }];
}

-(void)dbDeleteTable:(NSString *)tableName
{
    [self.databaseQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        @try {
            [DBHelper executeDeleteTable:tableName database:db];
        }
        @catch (NSException *exception) {
            // todo 异常处理
            *rollback = YES;
        }
        @finally {
        /* 在databasequeue 里的block不能close db，否则，该db就被close了 */
//            [db close];
        }
    }];
}


@end
